<?php
/**
 * Created by PhpStorm.
 * User: YAN
 * Date: 2017/7/13
 * Time: 17:01
 */

namespace App\Http\Controllers\API\Exam;


use App\Http\Controllers\Controller;
use App\Http\Requests\ExamImportRequest;
use App\Models\AdminLog;
use App\Models\Classes;
use App\Models\ClassStudent;
use App\Models\Exam;
use App\Models\Student;
use App\Models\StudentCourse;
use App\Models\StudentExam;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class ExamController extends Controller
{
    private $errorNum = 0;
    private $successNum = 0;
    private $user = 0;
    private $opening = '';

    /**
     * 导入考试
     * @param Request $request
     */

    public function import(Request $request)
    {
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "1024M");
        if ($request->ajax()) {
            $this->user = $request->get('user');
            $this->opening = $request->get('opening');
            $file = $request->file('file');
            if(!$this->opening){
                return response(['success' => 'false', 'message' => '尚未选择学期'],406);
            }
            // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
            $extension = $file->getClientOriginalExtension();
            $savePath = public_path('') . '/files_store';
            $filename = 'kaoshidaoru.' . $extension;
            $file->move($savePath, $filename);
//            $path = $file->store('avatars', 'uploads');
            Excel::load($savePath . '/' . $filename, function ($reader) {
                $reader1 = $reader->getSheet(0);
                $results = $reader1->toArray();
                foreach ($results as $key => $items) {
                    if ($key == 0 || empty($items[7])) {
                        continue;
                    }
                    \DB::beginTransaction();
                    try {

                        $coure = DB::table('courses')->where(['c_number' => trim($items[1]), 'serial_number' => trim($items[3])])->first();
                        if (!$coure) {
                            continue;
                        }
                        $times = explode(" ", $items[7]);
                        if (!empty($times[1])) {
                            $be_time = explode("-", $times[1]);
                        }
                        if (!empty($times[2])) {
                            $be_time = explode("-", $times[2]);
                        }
                        $exam = Exam::query()->where(['semester_id'=>$this->opening,'e_code' => trim($items[1]), 'serial_number' => trim($items[3])])->first();
//                        var_dump($times[0].$be_time[0]);die;
                        if (!$exam) {
                            $exam = new Exam();
                        }
                        $exam->c_id = $coure->id;
                        $exam->e_code = trim($items[1]);
                        $exam->e_name = $coure->c_name;
                        $exam->place = $items[8];
                        $exam->semester_id = $this->opening;
                        $exam->serial_number = $items[3];
                        $exam->begin = strtotime($times[0] . " " . $be_time[0]);
                        $exam->end = strtotime($times[0] . " " . $be_time[1]);
                        $exam->is_required = 1;
                        $exam->persons = $items[6];
                        if($items[3] >=97){
                            $exam->is_make_up =1;
                        }
                        if (!$exam->save()) {
                            throw new \Exception(var_dump($exam->getErrors()));
                        }
                        $students = StudentCourse::query()->where(['c_id' => $coure->id, 'semester_id' => $this->opening])->get();
                        if ($students) {
                            foreach ($students as $items) {
                                $log = StudentExam::query()->where(['e_id' => $exam->id, 's_id' => $items->s_id])->first();
                                if (!$log) {
                                    $log = new StudentExam();
                                    $log->e_id = $exam->id;
                                    $log->s_id = $items->s_id;
                                    if (!$log->save()) {
                                        throw new \Exception(var_dump($log->getErrors()));
                                    }
                                }
                            }
                        }
                        \DB::commit();
                        $this->successNum += 1;
                    } catch (\Exception $e) {
                        \DB::rollBack();
                        $this->errorNum += 1;
                    }
                }
                $logs = new AdminLog();
                $logs->admin = $this->user;
                $logs->logs = '导入考试信息，成功' . $this->successNum . '条，失败' . $this->errorNum . '条';
                $logs->save();
                if ($this->errorNum) {
                    return response($this->errorNum, 406);
                } else {
                    return response('导入成功', 200);
                }

            });
//            return ;
        }
    }

    /**
     * 导入成绩
     * @param Request $request
     */
    public function select(Request $request)
    {
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "1024M");
        if ($request->ajax()) {
            $this->user = $request->get('user');
            $file = $request->file('file');
            // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
            $extension = $file->getClientOriginalExtension();
            $savePath = public_path('') . '/files_store';
            $filename = 'chengjidaoru.' . $extension;
            $file->move($savePath, $filename);
//            $path = $file->store('avatars', 'uploads');
            Excel::load($savePath . '/' . $filename, function ($reader) {
                $reader1 = $reader->getSheet(0);
                $results = $reader1->toArray();
                //    dd($results);
                foreach ($results as $key => $items) {
                    if ($key == 0) {
                        continue;
                    }
                    $kch = $items[0];
                    $xh = $items[1];
                    $kxh = $items[3];
                    $kccj = $items[5];
                    $jdcj = $items[11];
                    $xm = $items[12];
                    $bj = $items[16];
                    $kcm = $items[29];
                    $xf = $items[36];
                    \DB::beginTransaction();
                    try {
                        if (!empty($kccj) && !empty($jdcj)) {
                            $exam = DB::table('exams')->where(['e_code' => trim($kch), 'serial_number' => trim($kxh)])->first();
                            if (!$exam) {
                                $exam = new Exam();
                                $exam->e_code = $kch;
                                $exam->serial_number = $kxh;
                                $exam->e_name = $kcm;
                                $exam->is_required = 1;
                                if($kxh >=97){
                                    $exam->is_make_up =1;
                                }
                                if (!$exam->save()) {
                                    throw new \Exception('考试保存失败');
                                }
                            }
                            $class = Classes::query()
                                ->where('c_name', $bj)
                                ->first();
                            if (!$class) {
                                $class = new Classes();
                                $class->c_name = $bj;
                                if (strpos($bj, "业务") !== false) {
                                    $class->type = 1;
                                } else {
                                    $class->type = 2;
                                }
                                if (!$class->save()) {
                                    throw new \Exception('班级创建失败');
                                }
                            }
                            $student = Student::query()->where('u_code', $xh)
                                ->first();
                            if (!$student) {
                                $student = new Student();
                                $student->u_name = $xm;
                                $student->u_code = $xh;
                                $student->school = '';
                                $student->access_token = str_random(60);
                                if (!$student->save()) {
                                    throw new \Exception('绑定学生失败');
                                }
                            }
                            ClassStudent::query()->where('s_id', $student->id)->delete();
                            $log = new ClassStudent();
                            $log->s_id = $student->id;
                            $log->c_id = $class->id;
                            if (!$log->save()) {
                                throw new \Exception('绑定学生学校失败');
                            }
                            $log = StudentExam::query()->where(['s_id' => $student->id, 'e_id' => $exam->id])->first();
                            if (!$log) {
                                $log = new StudentExam();
                                $log->e_id = $exam->id;
                                $log->s_id = $student->id;
                                $log->code = $kccj;
                                $log->e_jd_codes = $jdcj;
                                $log->credit = $xf;
                                if (!$log->save()) {
                                    throw new \Exception('绑定学生考试失败');
                                }
                            }
                        } else {
                            throw new \Exception('缺少考试成绩');
                        }
                        \DB::commit();
                        $this->successNum += 1;
                    } catch (\Exception $e) {
                        \DB::rollBack();
                        $this->errorNum += 1;
                    }
                }
                $logs = new AdminLog();
                $logs->admin = $this->user;
                $logs->logs = '导入考试成绩信息，成功' . $this->successNum . '条，失败' . $this->errorNum . '条';
                $logs->save();
                if ($this->errorNum) {
                    return response($this->errorNum, 406);
                } else {
                    return response('导入成功', 200);
                }
            });

//            return ;
        }
    }

    public function importStudent(Request $request)
    {
        return 'yes';
    }

    public function getList()
    {
        $Exams = Exam::query()->get();
        $result = [];
        if ($Exams) {
            foreach ($Exams as $items) {
                $result[$items->id] = $items->e_name;
            }
        }
        return $result;
    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $select = $request->get('select', '');
         $query = Exam::query()->with('Semesters')
             ->where('e_name', 'like', '%' . $queryString . '%');
        if (!empty($select)) {
            $query->where(['semester_id' => $select]);
        }
         $models = $query->paginate();
        return $models;
    }


    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new Exam();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update($id, Request $request)
    {
        $Exam = $this->findModel($id);
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '修改考试信息：'. $Exam->e_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        $Exam->fill($request->all());
        if ($Exam->save()) {
            return $Exam;
        } else {
            return response($Exam->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除考试信息：'. $model->e_name;
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = Exam::query()->where(['id'=>$id])->first();
        return $model;
    }
}